<?php

/**
 * Description of AzureCelebInit
 *
 * @author honza
 */

namespace Celebrio\FileSystem\Drivers;

use Nette\Object;
use \dibi;

use Celebrio\Core\IModuleInit;
use \Celebrio\Core\DummyInit;
use Celebrio\Core\DDL;
use Celebrio\FileSystem\Drivers\AzureStorageDriver;
use Celebrio\Core\ServiceProvider;
use Celebrio\FileSystem\IOException;
use Celebrio\FileSystem\Drivers\AzureCelebrio;
use \InvalidStateException;
use \InvalidArgumentException;


class AzureCelebrioInit extends DummyInit implements IModuleInit {
    
    public function changeConfig(array $configuration) {
        return $configuration;
    }


    public function init(array $configuration) {
        $accountName = $configuration["accountName"];
        $password = $configuration["password"];
        AzureCelebrio::setConnectionSettings($accountName, $password);
    }

    public function install(array $configuration) {
        $credentials = AzureCelebrio::areCredentialsValid($configuration["accountName"], $configuration["password"]);
        if(!$credentials) {
            throw new InvalidArgumentException("You have probably provided bad account name or password");
        }
        $dbDriver = ServiceProvider::getService("Celebrio-Database-IDatabase");
        $dbName = $dbDriver->getReflection()->getName();
        $dbName = \explode("\\", $dbName);
        $dbName = $dbName[\count($dbName)-1];
        DDL::execute(__DIR__ . "/initScripts/Azure-$dbName.sql");
        $this->initDriverStorage();
        
    }

    public function isAvailable() {
        return true;
    }
    
    public function formFields() {
        return array(
            array(
                "name" => "accountName", 
                "label" => "Account name:", 
                "type" => "text", 
                "required" => _('Please provide an account name.')
            ),
            array(
                "name" => "password", 
                "label" => "Password:", 
                "type" => "password", 
                "required" => _('Please provide a password.')
            )
            
        );
    }
    
    private function initDriverStorage() {
        $exists = dibi::fetch("
            SELECT [id_files_storage] 
            FROM [files_storages]
            WHERE [name_files_storage] = %s", "azureCelebrio");
        
        if(!$exists) {
            dibi::query("
                INSERT INTO [files_storages]
                ([name_files_storage]) VALUES (%s)", "azureCelebrio");
        }
    }

}
